package hua.mtreader.feature.bookshelf.model;

import com.google.gson.Gson;

import java.io.IOException;

import hua.mtreader.common.utils.Constant;
import hua.mtreader.common.utils.ToolsPreferences;
import hua.mtreader.feature.bookshelf.bean.BookshelfRepsone;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/3/22.
 */
public class BookshelfModelImpl implements IBookshelfModel {


    private OkHttpClient client;

    public BookshelfModelImpl() {
        client = new OkHttpClient();
    }

    @Override
    public void getBooks(final BookshelfListener bookshelfListener) {

        String url = Constant.root_url2 + "bookshelf";
        String token = ToolsPreferences.getPreferences(ToolsPreferences.USER_TOKEN);

        FormBody formBody = new FormBody.Builder()
                .add("sd", token)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Gson gson = new Gson();
                BookshelfRepsone repsone = gson.fromJson(json, BookshelfRepsone.class);
                bookshelfListener.onLoadBooksSuccess(repsone);
            }
        });
    }

    public interface BookshelfListener{

        void onLoadBooksSuccess(BookshelfRepsone repsone);
    }

}
